import { defineStore } from 'pinia'
import { ref } from 'vue'
import { loginAPI,registerAPI } from '@/apis/user'
import { useCartStore } from './cartStore'
import { mergeCartAPI } from '@/apis/cart'
import { ElMessage } from 'element-plus'

export const useUserStore = defineStore('user', () => {

  const userInfo = ref({})
  const cartStore = useCartStore()

  const getUserInfo = async ({ account, password }) => {
    const res = await loginAPI({ account, password })
    userInfo.value = res.data.data
    if (cartStore.cartList.length > 0) {
      //合并购物车的操作
      try {
        await mergeCartAPI(cartStore.cartList.map(item => {
          return {
            skuId: item.skuId,
            selected: item.selected,
            count: item.count
          }
          }), userInfo.value.id)
      } catch(e) {
        console.error('合并购物车失败', e)
      }
    }
    
    //获取最新的购物车列表
    try {
      await cartStore.updateNewList()
    } catch(e) {
      console.error('获取最新购物车列表失败', e)
      }
    } 

  const clearUserInfo = () => {
    userInfo.value = {}
    cartStore.clearCart()
  }
  const registerUser = async ({ account, nickname, password }) => {
    await registerAPI({ account, nickname,password })
  }
  return {
    userInfo,
    getUserInfo,
    clearUserInfo,
    registerUser
  }
}, {
  persist: true,
})
